package com.googlecode.javatools.classparser.impl;

import java.io.DataInput;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import com.googlecode.javatools.classparser.AccessFlagParser;
import com.googlecode.javatools.classparser.ClassInfoParser;
import com.googlecode.javatools.classparser.types.ClassInfo;
import com.googlecode.javatools.classparser.types.ConstantPool;
import com.googlecode.javatools.classparser.types.impl.ClassInfoImpl;

public class ClassInfoParserImpl implements ClassInfoParser
{
	private final AccessFlagParser accessFlagParser;

	public ClassInfoParserImpl(final AccessFlagParser accessFlagParser)
	{
		this.accessFlagParser = accessFlagParser;
	}

	public ClassInfo parse(final DataInput in, final ConstantPool constantPool) throws IOException
	{
		final int accessFlag = in.readUnsignedShort();
		final boolean isClassAbstract = accessFlagParser.isAbstract(accessFlag);
		final boolean isInterface = accessFlagParser.isInterface(accessFlag);
		final boolean isPublic = accessFlagParser.isPublic(accessFlag);

		final int classNameIndex = in.readUnsignedShort();
		final String fullyQualifiedClassName = constantPool.valueAtIndex(classNameIndex);
		final int superClassNameIndex = in.readUnsignedShort();
		final String fullyQualifiedSuperClassName = constantPool.valueAtIndex(superClassNameIndex);

		final int interfaceCount = in.readUnsignedShort();

		final List<String> interfaceNames = new ArrayList<String>(interfaceCount);

		for (int i = 0; i < interfaceCount; i++)
		{
			final int entryIndex = in.readUnsignedShort();
			interfaceNames.add(constantPool.valueAtIndex(entryIndex));
		}

		return new ClassInfoImpl(fullyQualifiedClassName, fullyQualifiedSuperClassName, interfaceNames,
				isClassAbstract, isInterface, isPublic);
	}

}
